package com.sky.service.impl;

import com.sky.context.BaseContext;
import com.sky.entity.AddressBook;
import com.sky.mapper.AddressBookMapper;
import com.sky.service.AddressService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class AddressServiceImpl implements AddressService {
    @Autowired
    private AddressBookMapper addressBookMapper;
    @Override
    public void insertAddress(AddressBook addressBook) {
        addressBookMapper.insert(addressBook);
    }

    @Override
    public List<AddressBook> listByUserId(long userId) {
        return addressBookMapper.listByUserId(userId);

    }

    @Override
    public AddressBook getDefault(long userId) {
        return addressBookMapper.getDefault(userId);
    }

    @Override
    @Transactional
    public void setDefault(Long id) {
        // 先通过获取默认地址，若地址对象不为空，将返回的对象默认信息设为0
        AddressBook address = addressBookMapper.getDefault(BaseContext.getCurrentId());
        if (address != null){
            address.setIsDefault(0);
            addressBookMapper.update(address);
        }
        address = addressBookMapper.getById(id);
        address.setIsDefault(1);
        addressBookMapper.update(address);
        // 再通过地址id将地址对象默认设为1
    }

    @Override
    public void delete(Long id) {
        addressBookMapper.deleteById(id);
    }

    @Override
    public AddressBook getById(Long id) {
        return addressBookMapper.getById(id);
    }

    @Override
    public void update(AddressBook addressBook) {
        addressBookMapper.update(addressBook);
    }
}
